package cn.tedu.charging.order.rabbit;

import cn.tedu.charging.order.config.RabbitConfiguration;
import cn.tedu.charging.order.pojo.po.OrderMQPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitMQOrderProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     */
    public void sendOrder(OrderMQPO orderMQPO){
        //channel.basicPublish(exchange,routingKey,properties,message.getBytes());
        rabbitTemplate.convertAndSend(RabbitConfiguration.EXCHANGE_NAME,
                RabbitConfiguration.ROUTING_KEY,orderMQPO);

        // confirm机制
        //设置RabbitMQ return 回调类 并回执
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            log.debug("returnedMessage:{}",returnedMessage);
        });
        //设置RabbitMQ的确认机制的回调类,保证消息发送的时候不丢
        rabbitTemplate.setConfirmCallback((data,ack,cause)->{
            log.debug("data:{},ack:{},cause:{}",data,ack,cause);
            if(ack){
                log.debug("RabbitMQ成功收到了消息");
            }else {
                log.debug("RabbitMQ没成功收到了消息,打日志,进行重试,重新发送,如果重试多次不成功,需要告警",cause);
            }
        });
    }


}
